import { ref, unref, watchEffect } from 'vue'

export function useForm(formProps) {
  const formRef = ref(null)

  let stopWatch

  function register(instance) {
    formRef.value = instance

    stopWatch && stopWatch()

    stopWatch = watchEffect(() => {
      formProps && instance.setProps(formProps)
    })
  }

  function getFormInstance() {
    const form = unref(formRef)
    if (!form) {
      console.error(
        'The form instance has not been obtained yet, please make sure the form is presented when performing the form operation!'
      )
    }
    return form
  }

  const method = {
    // 更新查询按钮/重置按钮状态，判断是否显示隐藏
    updateBtnStatus: (...args) => getFormInstance().updateBtnStatus(...args),
    validate: () => getFormInstance().validate(),
    clearValidate: () => getFormInstance().clearValidate(),
    validateField: () => getFormInstance().validateField(),
    reset: () => getFormInstance().reset(),
    getFieldValues: () => getFormInstance().getFieldValues(),
    setFieldValues: e => getFormInstance().setFieldValues(e),
    updateSchema: e => getFormInstance().updateSchema(e),
    insetSchema: (...args) => getFormInstance().insetSchema(...args),
    removeSchemaByFiled: field => getFormInstance().removeSchemaByFiled(field),
    resetSchemas: () => getFormInstance().resetSchemas(),
    updateSchemaByIndex: (index, e) => getFormInstance().updateSchemaByIndex(index, e)
  }

  return [register, method]
}
